#function(result)
local dparam = result.dparam;

logger.log_message("EMP postprocess ... ");
logger.log_message("******************* ");

// 输入文件的完整路径
local input_file  = result.dparam.input_file;
local output_file = result.dparam.output_file;
local param_file = result.dparam.param_file;
logger.log_message("FULLPATH OF INPUT FILE: %s", input_file)
logger.log_message("FULLPATH OF PARAM FILE: %s", param_file)
// 获取结果所在的文件夹
logger.log_message("FULLPATH OF OUTPUT FILE: %s", output_file);

// 准备输出信息头
local ResultInfo = table
{
    // 预设计信息
    sim_project_info : table 
    {
        pre_design_name : "predesign_name";    // 预设计名称
        sim_scene : "scene_name";              // 场景名称
        name : "project_name";                 // 工程名称
		geometry_file_name : []     //  模型名称
    };

    result_info : [ ]

};
ResultInfo.sim_project_info.name = fs.filename(input_file).name;
ResultInfo.sim_project_info.sim_scene = 3; // 2 表示HEMP/NEMP
// 读取输入信息

local default_result_info_node = io.handler.json.load("app:/scripting/solver/EMP/default_result_info_node.json");
//local dflag=0;  //读取参数来源 0 来源于mxd,1 来源于json配置文件

//local param = io.handler.json.load(input_file);
local param;
if(fs.exists(param_file)==1)
{
    param = io.load_var(param_file);
    logger.log_message("Load Param Success")
}
else
{
    
    logger.log_message("Load Param Failure!")
    return ;
}

local check_folder=function(target_folder)
{
    switch(fs.exists(target_folder))
        {
        case 0:
            // 不存在，创建文件夹
            fs.mkdir(target_folder);
            logger.log_message("Create folder: %s", target_folder);
        case 1:
            // 错误是个文件
            logger.log_error("Cannot create folder: %s", target_folder);
            break;
        case 2:
        }
}

local tb_fun=exec("app:/scripting/solver/EMP/Save_format_file.mx");
/*
*tb_fun.Save_1d(fn,data,title,_format)
*   fn 文件名
*   data 需要保存的数据
*   title 数据头文件 
*   _format指定输出格式 默认 "%.7e"
*tb_fun.Save_2d(fn,u,v,data,title,_format)
*   fn 文件名
*   u 局部坐标u
*   v 局部坐标v
*   data 保存的二维电磁场数据
*   title 数据头文件
*   _format 指定输出格式 默认 "%.7e"
*/
// 处理 ELECTRIC_FIELD_IN
local check_type=function(param,key)
{
    if(!is_nil(param[key]) && numel(param[key])>0)
    {
        logger.log_message("The Type:%s",key);
       // return eval1(key, param);
        return param[key];
    }
    else
    {
        logger.log_message("The Type:%s is Not Found or Definited!",key);
        return 1;
    }
}


logger.log_message("Processing domain [ELECTRIC_FIELD_IN] ... ");
local resultPath=?(is_nil(param.output.fpath),dparam.str_macro.get("$(FULLPATH)")..".data/",param.output.fpath);
local probe = check_type(param,"probe")
local model = check_type(param,"model");
if(typeid(model)==10)
{
	for(i,v in model)
	{
	ResultInfo.sim_project_info.geometry_file_name.push(v.file);
	}
}
if(typeid(probe)==10)   //array_variant
{
     local Efiled=table{
            Ex:0;
            Ey:1;
            Ez:2;
            Hx:3;
            Hy:4;
            Hz:5;
            EVec:6;
            HVec:7;
            `EVec&HVec`:8
        };
    local unitname = ["V/m", "V/m", "V/m", "A/m", "A/m", "A/m", "V/m", "A/m"];
    local monitor_type=table{
        `0`:"None";
        `1`:"point";
        `2`:"cartesian_surface";
        `3`:"cartesian_volume";
        `4`:"spherical"
    };
    for(i,v in probe)
    {
        local info = clone(default_result_info_node); //读取默认信息文件
        /* result_type 类型
        * ****************
        * 0 - 体电场分布
        * 1 - 面电场分布
        * 2 - 点电场
        * 3 - 表面电磁场分布
        * 4 - 表面电流分布
        * 5 - 空间电势分布
        * 6 - 表面电势分布
        * 7 - 方向图
        * 8 - S参数
        * 9 - 驻波比
        * 10 - 线缆电压
        * 11 - 线缆电流
        * 12 - 干扰关联矩阵
        * 13 - SAR仿真
        * 14 - 静电附着点
        */

        
        /* result_data_type 类型
        * ****************
        * 0 - 标量
        * 1 - 复数（实部 + 虚部）
        * 2 - 复数（幅度 + 相位）
        * 3 - 图片（Image）
        */
       
    
       if(typeid(v.mtype)==2) //integer
       {
           logger.log_message("Processing Field_Point Group:%s Definition form:%s",v.name,v.inputtype);
           info.result_type = 2;
           info.result_folder_path = "";
           local Position=?(is_nil(v.file),[],v.file);
           local target_folder = resultPath..v.name .. "_td";
           check_folder(target_folder)
           info.result_data_folder_name_td = v.name .. "_td";
           info.result_data_type = 0;
           info.time_unit = util.utname(dparam.UT);
           info.field_monitor_type = 1;   
           local header = table();
           header.datafile_type = ".csv";
            header.unit = table
            {
                coordinate : util.ulname(dparam.UL);
                E_field    : "V/m";
                H_field    : "A/m";
                frequency  : util.ufname(dparam.UF);
                time : util.utname(dparam.UT)
            };
            header.Domain_info = "Time-domain";
            local probe_data=result[v.name];
            info.time_data = probe_data[0].time_record;
            local header_file = fs.makepath("header.json", target_folder);
            header.field_monitor_type=monitor_type[v.mtype];
            header.field_monitor_sample_info=[];
			header.field_monitor_name=[];
			local name =[];
            for(local i=0;i<numel(probe_data);++i)
            {
                local pos=probe_data[i].pos;
                local sample_info=table{
                    sta_x:string.format("%.2f",pos[0]);
                    end_x:"";
                    num_x:"";
                    sta_y:string.format("%.2f",pos[1]);
                    end_y:"";
                    num_y:"";
                    sta_z:string.format("%.2f",pos[2]);
                    end_z:"";
                    num_z:"";
                };
				name = v.name;
				if(v.inputtype=="data")
				{
					name = v.data[i][0];
				}
                local fn = fs.makepath(string.format(name..header.datafile_type, i), target_folder);
                logger.log_message("Write_file: %s", fn);
                local index=Efiled[v.fieldtype];
                local tmp_data=[];
                local title=[];
                local h1=["time",util.utname(dparam.UT),"key"];
                if(index !=6 && index !=7 && index !=8)
                {
                    tmp_data=cat(1,info.time_data,probe_data[i].datas[index]);
                    
                    local h2=["mag("..v.fieldtype..")",unitname[index],"value"];
                    title = pack(h1,h2);
                    tb_fun.Save_1d(fn,tmp_data,title);
                }else if(index ==6)
                {
                    tmp_data=cat(1,info.time_data,probe_data[i].datas[0],probe_data[i].datas[1],probe_data[i].datas[2]);
                    local h2=["mag(Ex)",unitname[0],"value"];
                    local h3=["mag(Ey)",unitname[1],"value"];
                    local h4=["mag(Ez)",unitname[2],"value"];
                    title = pack(h1,h2,h3,h4);
                    tb_fun.Save_1d(fn,tmp_data,title);
                }else if(index ==7)
                {
                    tmp_data=cat(1,info.time_data,probe_data[i].datas[3],probe_data[i].datas[4],probe_data[i].datas[5]);
                    local h2=["mag(Hx)",unitname[3],"value"];
                    local h3=["mag(Hy)",unitname[4],"value"];
                    local h4=["mag(Hz)",unitname[5],"value"];
                    title = pack(h1,h2,h3,h4);
                    tb_fun.Save_1d(fn,tmp_data,title);
                }
                header.field_monitor_sample_info.push(sample_info);
                if(v.inputtype=="data")
                {header.field_monitor_name.push(v.data[i][0]);}
            }
            //io.writefile(header_file, io.to_json(header));
            ResultInfo.result_info.push(info);
       }
       else
       {
        logger.log_message("Processing Field_Inner Group:%s Definition form:%s",v.name,v.inputtype);
        for(local i=0;i<numel(v.mtype);i++)
          { 
            info.result_type = ?(v.mtype[i]==2,1,?(v.mtype[i]==3,0,-1)); //2D-->1;3D-->0;0D-->-1
            if(info.result_type ==-1||info.result_type ==0) //屏蔽3D与0D
            {
                continue;
            }
            info.result_folder_path = "";
            local probe_data = result[v.data[i][0]]; 
            local target_folder;     
            if(v.type=="FREQ_DOMAIN")
            {
                target_folder = resultPath..v.data[i][0] .."_fd";
                info.result_data_folder_name_fd = v.data[i][0] .."_fd";
                info.result_data_type = 1;   //0 标量 1 复数（实部+虚部)
                info.frequency_unit = util.ufname(dparam.UF);
                info.frequency_data = v.freq;
            }else
            {
                target_folder = resultPath..v.data[i][0] .. "_td";
                info.result_data_folder_name_td = v.data[i][0] .. "_td";
                info.result_data_type = 0;
                info.time_unit = util.utname(dparam.UT);
                info.time_data = ?(is_nil(probe_data[0].time),probe_data[0].time,v.time);//debug 可能设置时间不对
            }
            check_folder(target_folder)
            info.field_monitor_type = 2;   
            local header = table();
            header.datafile_type = "csv";
            header.unit = table
            {
                coordinate : util.ulname(dparam.UL);
                E_field    : "V/m";
                H_field    : "A/m";
                frequency  : util.ufname(dparam.UF);
                time : util.utname(dparam.UT)
            };
            header.Domain_info = v.type;
            local header_file = fs.makepath("header.json", target_folder);
            header.field_monitor_type=monitor_type[v.mtype[i]];
            header.field_monitor_sample_info=[];
			header.field_monitor_name=[];
            header.field_monitor_freq=[];
            if(v.type=="FREQ_DOMAIN")
            {
                local freqs = v.freq;
                local pos = [v.data[i][1],v.data[i][2],v.data[i][3],v.data[i][4],v.data[i][5],v.data[i][6]];
                local monitor_name=v.data[i][0];
                local plane,nu,nv,nn,uc,vc,num,sample_info;
                for(local index=0;index<numel(freqs);index++)
                {
                    local fn = fs.makepath(string.format(v.data[i][0].."_%03d."..header.datafile_type, index), target_folder);
                    if(numel(v.fieldtype)==2 && v.mtype[i] ==2 ) //2D Ex,Ey,Ez,Hx...
                    {
                        local retf = tb_fun.Slice_F_single(probe_data[0],index,v.fieldtype);
                        local h1 = [retf.info[0],util.ulname(dparam.UL),"key"];
                        local h2 = [retf.info[1],util.ulname(dparam.UL),"key"];
                        local h3 = ["Re("..v.fieldtyp..")","None","value"];
                        local h4 = ["Im("..v.fieldtyp..")","None","value"];
                        local title =pack(h1,h2,h3,h4);
                        local data =retf.data;
                        uc =retf.uc;
                        vc = retf.vc;
                        plane = retf.plane;
                        nu=numel(uc);
                        nv=numel(vc);
                        tb_fun.Save_2d(fn,uc,vc,data,title);
                    }
                    else if (v.mtype[i]==2)   //2D Evec Hvec Evec&Hvec
                    {
                            local retf = tb_fun.Slice_F_vec(probe_data[0],index,v.fieldtype,pos);
                            local h1 =[retf[0].info[0],util.ulname(dparam.UL),"key"];
                            local h2 =[retf[0].info[1],util.ulname(dparam.UL),"key"];
                            if(numel(retf)==3)
                            {
                                local h3 =["Re("..v.fieldtype[0].."x)","None","value"];
                                local h4 =["Im("..v.fieldtype[0].."x)","None","value"];
                                local h5 =["Re("..v.fieldtype[0].."y)","None","value"];
                                local h6 =["Im("..v.fieldtype[0].."y)","None","value"];
                                local h7 =["Re("..v.fieldtype[0].."z)","None","value"];
                                local h8 =["Im("..v.fieldtype[0].."z)","None","value"];
                                local title = pack(h1,h2,h3,h4,h5,h6,h7,h8);
                                local data = pack(retf[0].data,retf[1].data,retf[2].data);
                                uc = retf[0].uc;
                                vc = retf[0].vc;
                                nu=numel(uc);
                                nv=numel(vc);
                                plane = retf[0].plane;
                                tb_fun.Save_2d(fn,uc,vc,data,title);
                            }else
                            {
                                local h3 =["Re(Ex)","None","value"];
                                local h4 =["Im(Ex)","None","value"];
                                local h5 =["Re(Ey)","None","value"];
                                local h6 =["Im(Ey)","None","value"];
                                local h7 =["Re(Ez)","None","value"];
                                local h8 =["Im(Ez)","None","value"];
                                local h9 =["Re(Hx)","None","value"];
                                local h10 =["Im(Hx)","None","value"];
                                local h11 =["Re(Hy)","None","value"];
                                local h12 =["Im(Hy)","None","value"];
                                local h13 =["Re(Hz)","None","value"];
                                local h14 =["Im(Hz)","None","value"];
                                local title = pack(h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13,h14);
                                local data = pack(retf[0].data,retf[1].data,retf[2].data,retf[3].data,retf[4].data,retf[5].data);
                                uc = retf[0].uc;
                                vc = retf[0].vc;
                                plane = retf[0].plane;
                                nu=numel(uc);
                                nv=numel(vc);
                                tb_fun.Save_2d(fn,uc,vc,data,title);
                            }
                    }else   //3D 无用  前面已屏蔽
                    {
                        logger.log_message("%s is 3D probe！No deal!",v.data[i][0]);
                        local vpos = probe_data[0].data[0].vpos;
                        local nu = numel(vpos[0]);
                        local nv = numel(vpos[1]);
                        local nn = numel(vpos[2]);
                        pos = [vpos[0][0],vpos[1][0],vpos[2][0],vpos[0][end],vpos[1][end],vpos[2][end]];
                    }            
                }
                if (v.mtype[i]==2)  //2D 
                {
                    if(plane==2)
                    {
                        num=[nu,nv,1];
                    }else if(plane==1)
                    {
                        num=[nu,1,nv];
                    }else                     
                    {
                        num=[nu,nv,1];
                    }
                    sample_info=table{
                        sta_x:pos[0];
                        end_x:pos[3];;
                        num_x:num[0];
                        sta_y:pos[1];
                        end_y:pos[4];;
                        num_y:num[1];
                        sta_z:pos[2];
                        end_z:pos[5];
                        num_z:num[2];
                    };
                }
                else  //3D
                {
                    sample_info=table{
                        sta_x:pos[0];
                        end_x:pos[3];;
                        num_x:nu;
                        sta_y:pos[1];
                        end_y:pos[4];;
                        num_y:nv;
                        sta_z:pos[2];
                        end_z:pos[5];
                        num_z:nn;
                    };
                }
                 header.field_monitor_freq=v.freq;
                 header.field_monitor_sample_info.push(sample_info);
                 header.field_monitor_name.push(v.data[i][0]);
                 //io.writefile(header_file, io.to_json(header));
                 info.field_unit = header.unit;
                 info.field_monitor_sample_info= sample_info;
                 ResultInfo.result_info.push(info);
            }
            else
            {
                local plane,nu,nv,nn,uc,vc,num,sample_info,strinfo,data;
                 if(v.mtype[i]==2)    //2D -Time_domon
                 {
                    local ts = probe_data[0].time;
                    local plane = probe_data[0].coord.plane;
                    local cs = [probe_data[0].coord.x,probe_data[0].coord.y,probe_data[0].coord.z];
                    local pos = [v.data[i][1],v.data[i][2],v.data[i][3],v.data[i][4],v.data[i][5],v.data[i][6]];
                    local num =[numel(cs[0]),numel(cs[1]),numel(cs[2])];
                    local index=Efiled[v.fieldtype];
                    local fnTable=probe_data[0].data_fn;
                    for(local jj=0;jj<numel(ts);jj++) //处理各个时刻
                    {
                        local oriPath = dparam.str_macro.get("$(FULLPATH)")..".data/";
                        datasheet=io.load_var(oriPath..fnTable[jj]);
                        local fn = fs.makepath(string.format("%05d."..header.datafile_type, jj), target_folder);
                        switch(plane)
                        {
                            case 0: //YOZ
                            {
                                data =reshape(datasheet.data,num[1],num[2]);
                                strinfo ="YZ";
                                uc = cs[1];
                                vc = cs[2];
                                nu =numel(uc);
								nv =numel(vc);
								num=[nu,nv,1];
                            }
                            case 1: //ZOX
                            {
                                data = reshape(datasheet.data,num[0],num[2]);
                                strinfo ="XZ";
                                uc = cs[0];
                                vc = cs[2];
                                nu =numel(uc);
								nv =numel(vc);
								num=[nu,1,nv];
                            }
                            case 2: //XOY
                            {
                                data = datasheet.data;
                                strinfo ="XY";
                                uc = cs[0];
                                vc = cs[1];
                                nu =numel(uc);
								nv =numel(vc);
								num=[nu,nv,1];
                            }
                            default:
                                //throw "invalid_plane_id";
                                logger.log_message("invalid_plane_id:%d",plane);
                        }
                        local h1 = [strinfo[0],util.ulname(dparam.UL),"key"];
                        local h2 = [strinfo[1],util.ulname(dparam.UL),"key"];
                        local h3=["mag("..v.fieldtype..")",unitname[index],"value"];
                        local title = pack(h1,h2,h3);
                        tb_fun.Save_2d(fn,uc,vc,data,title);

                    }
                    sample_info=table{
                        sta_x:pos[0];
                        end_x:pos[3];;
                        num_x:num[0];
                        sta_y:pos[1];
                        end_y:pos[4];;
                        num_y:num[1];
                        sta_z:pos[2];
                        end_z:pos[5];
                        num_z:num[2];
                    };
                    header.field_monitor_time=ts;
                    header.field_monitor_name.push(v.data[i][0]);
                    //io.writefile(header_file, io.to_json(header));
                    //info.field_unit = header.unit;
                    info.field_monitor_sample_info= sample_info;
                    ResultInfo.result_info.push(info);
                 }
                 else    //3D -Time_domo
                 {
                     logger.log_message("%s is 3D probe！No deal",v.data[i][0]);
                    
                     /*
                     local idata = probe_data[0].smartdata_vol.idata.data;
                     local flg_field = probe_data[0].smartdata_vol.idata.flg_field;
                     local vpos = probe_data[0].smartdata_vol.idata.data[0].vpos;
                     local Enum = numel(idata); //处理几个分量
                     local nu = numel(vpos[0]);
                     local nv = numel(vpos[1]);
                     local nn = numel(vpos[2]);
                     local fn = fs.makepath(string.format("%05d."..header.datafile_type, index), target_folder);
                     local index=Efiled[v.fieldtype];
                     for(local cn1=0;cn1<Enum;cn1++)
                     {
                          
                        local fnTable=resultPath..idata.data[cn1].data_fn;
                        local nw=numel(fnTable)
                        for(local cn2=0;cn2<nw;cn2++)
                        {
                            datasheet=io.load_var(fnTable[cn2]);
                        }
                        
                     }
                     */
                 }
            }
            }
       }
    }
}
local cable = check_type(param,"cable");
if(typeid(probe)==10)   //array_variant
{
    logger.log_message("Processing domain [Cable] ... ");
    local info = clone(default_result_info_node); //读取默认信息文件
        info.result_type = 10;
        info.result_folder_path = "";
        local target_folder =resultPath.."cable";
        check_folder(target_folder);
        info.result_data_folder_name_td = "cable";
        info.result_data_type = 0;
        info.time_unit = util.utname(dparam.UT);
        local header = table();
        header.datafile_type = "csv";
        header.unit = table
        {
            coordinate : util.ulname(dparam.UL);
            E_field    : "V/m";
            H_field    : "A/m";
            frequency  : util.ufname(dparam.UF);
            time : util.utname(dparam.UT)
        };
        header.Domain_info = "Time-domain";
        local header_file = fs.makepath("header.json", target_folder);
        header.cable_sample_info=[];
        header.cable_name=[];
		local name=[];
    for(local ii=0;ii<numel(cable);ii++)
    {
        
        local probe_data=result["cable"..ii];   
        name=cable[ii].name;
		header.cable_name.push("cable"..ii);
        local V=probe_data[0].data;
        local Time_record=probe_data[0].time_record;
        
        local dt=Time_record.dt;
        local tmin=Time_record.t0;
        local tmax=dt*(length(V)-1);
        local ts=transpose(linspace(tmin,tmax,length(V)));
        local R=50;
        local I=V/R;
        local fn=fs.makepath(name.."_Voltage.csv", target_folder);
        logger.log_message("Write_file: %s", fn);
        local tmp_data=[];
        local title=[];
        local h1=["time",util.utname(dparam.UT),"key"];
        tmp_data=cat(1,ts[:],V);          
        local h2=[name.."_voltage","V","value"];
        title = pack(h1,h2);
        tb_fun.Save_1d(fn,tmp_data,title);
        fn=fs.makepath(name.."_Current.csv", target_folder);
        logger.log_message("Write_file: %s", fn);
        tmp_data=[];
        title=[];
        h1=["time",util.utname(dparam.UT),"key"];
        tmp_data=cat(1,ts[:],I);          
        h2=[name.."_current","A","value"];
        title = pack(h1,h2);
        tb_fun.Save_1d(fn,tmp_data,title);
        info.time_data = ts;
    }
    //io.writefile(header_file, io.to_json(header));
    ResultInfo.result_info.push(info);
}

local result_info = io.to_json(ResultInfo);
io.writefile(output_file, result_info);
